package com.zyylr.classroomreservationsystem.activity;

import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.zyylr.classroomreservationsystem.consts.GlobalConsts;
import com.zyylr.classroomreservationsystem.utils.ActivityCollector;
import com.zyylr.classroomreservationsystem.utils.LogoutBroadcastReceiver;

/**
 * 我的活动公共基类，其他活动继承此类，用于实现退出登录功能
 */
public class MyBaseCompatActivity extends AppCompatActivity {
    protected LogoutBroadcastReceiver localReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //创建活动时，将其加入管理器中
        ActivityCollector.addActivity(this);
    }

    /**
     * 我们始终需要保证只有处于栈顶的活动才能接收到这条广播，
     * 非栈顶的活动不应该也没有必要去接收这条广播
     * ——《第一行代码 P190》
     */
    @Override
    protected void onResume() {
        super.onResume();
        //活动继续，即回到栈顶，为所有继承此类的活动注册广播接收器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(GlobalConsts.BROADCAST_LOGOUT);
        localReceiver = new LogoutBroadcastReceiver();
        registerReceiver(localReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //活动暂停，取消注册广播接收器
        if (localReceiver != null) {
            unregisterReceiver(localReceiver);
            localReceiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁活动时，将其从管理器中移除
        ActivityCollector.removeActivity(this);
    }
}
